package com.haze.lt_file_api.web.controller;

import com.haze.lt_file_api.web.model.FileInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("files")
public class FileController {

    // 文件存储的路径，可以根据需求修改
    @Value("${file.cdn-root}")
    private String cdnRoot;

    // 查询文件列表
    @GetMapping("{folder}/list")
    public ResponseEntity<Object> listFiles(@PathVariable String folder) {
        String targetDir = cdnRoot + "\\" + folder;
        File dir = new File(targetDir);
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdirs();
        }

        File[] fileArray = dir.listFiles();
        if (fileArray == null) {
            return new ResponseEntity<>("没有文件", HttpStatus.NO_CONTENT);
        }

        // 将文件转换为 FileInfo 对象列表
        List<FileInfo> files = Arrays.stream(fileArray).filter(File::isFile) // 只处理文件
                .map(file -> new FileInfo(file.getName(), file.lastModified(), file.length(), file.getAbsolutePath())).sorted(Comparator.comparingLong(FileInfo::getLastModified).reversed()).collect(Collectors.toList());

        // 按 lastModified 排序，降序

        // 格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        files.forEach(file -> file.setFormattedLastModified(sdf.format(new Date(file.getLastModified()))));

        return new ResponseEntity<>(files, HttpStatus.OK);
    }

    // 上传文件
    @PostMapping("{folder}/upload")
    public ResponseEntity<Object> uploadFile(@PathVariable String folder, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("请选择一个文件", HttpStatus.BAD_REQUEST);
        }
        Map<String, Object> resMap = new HashMap<>();
        try {
            // 获取文件名并保存文件
            String fileName = file.getOriginalFilename();
            Path path = Paths.get(cdnRoot + "\\" + folder, fileName);
            Files.copy(file.getInputStream(), path);

            resMap.put("success", true);
            resMap.put("message", "文件上传成功: " + fileName);
            return new ResponseEntity<>(resMap, HttpStatus.OK);
        } catch (IOException e) {
            resMap.put("success", false);
            resMap.put("message", "文件上传失败: " + e.getMessage());
            return new ResponseEntity<>(resMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 删除文件
    @DeleteMapping("{folder}/delete/{fileName}")
    public ResponseEntity<String> deleteFile(@PathVariable String folder, @PathVariable String fileName) {
        try {
            Path path = Paths.get(cdnRoot + "\\" + folder, fileName);
            Files.delete(path);

            return new ResponseEntity<>("文件删除成功: " + fileName, HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>("文件删除失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
